class ApplicationController < ActionController::Base
  protect_from_forgery
  helper_method :current_user

  force_ssl

  require 'net/http'
  
  private

  def current_user
    current_user ||= User.find(session[:user_id]) if session[:user_id]
  end

  def is_admin
    if current_user.blank?         
        redirect_to root_path
    elsif current_user.user_type_id != 1
        redirect_to root_path
    end
  end

  def check_token
    # session["token"] = nil
    if session["token"].nil? or session["token"].blank? 
      get_token
    end
  end

  def get_token
    uri = URI('http://api.master18.tiket.com/apiv1/payexpress?method=getToken&secretkey=155894b2968bfadd6e72e225265ff86c&output=json')
    res = Net::HTTP.get_response(uri)
    json = JSON.parse(res.body)
    session["token"] = json["token"]
    json["token"]
  end

  def hotel_promo
    uri = URI('http://api.master18.tiket.com/search/search_area?uid=city:178&token='+get_token.to_s+'')
    res = Net::HTTP.get_response(uri)
    @json = JSON.parse(res.body)
  end
  
  def hotel_results(uri,params)
    uri.query = URI.encode_www_form(params)
    res = Net::HTTP.get_response(uri )
    @json = JSON.parse(res.body)
    if @json["results"]
      @results = @json["results"]["result"].paginate(per_page: 10, page: params[:page] )
    else
      @results = nil
    end  
  end

  def hotel_detail_results(uri,params)
    uri.query = URI.encode_www_form(params)
    res = Net::HTTP.get_response(uri )
    @json = JSON.parse(res.body)
    if @json["results"]
      @results = @json
    else
      @results = nil
    end  
  end
end
